var gridObj;
var project = {

    /* 初始化 */
    init: function() {
        var self = this;
        self.initEvent();
        self.initForm();
        self.initGrid();
        self.validate();
    },

    /* 初始化表单 */
    initForm: function(){
        var self = this;
        // 日期插件
        $('#startFrom,#startTo,#endFrom,#endTo').datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 2,
            minView: 2,
            autoclose: true,
            language: 'zh-CN',
            todayBtn: true,
        });
        // 初始化下拉框
        self.getProjectUsers();
        self.getProjectMembers();

    },

    /* 初始化事件 */
    initEvent: function() {
        var self = this;

        /* 点击搜索 */
        $('#search').click(function() {
            var params = $('#projectForm').serializeArray();
            self.query(params, gridObj);
        });

        /* 点击添加 */
        $('#add').click(function() {
            self.showDialog('新增项目');
        });

        /* 点击批量删除 */
        $('#delete').click(function() {
            self.batchDelete();
        });

        /* 点击确认 */
        $('#confirm').click(function() {
            /*if(self.validate() && self.code) {
                self.confirm();
            }*/
            if($('#dialogForm').valid()) {
                self.confirm();
            }
        });

        /**/
        $('#isValid, #status').change(function() {
            var params = $('#projectForm').serializeArray();
            self.query(params, gridObj);
        });

        /**/
        /*$('#editProjectName').keyup(function() {
            self.checkProjectName();
        });*/

        /* 清空日期 */
        $('.clearDate').click(function(){
            $(this).prev().val('');
        });

        /*$('#editProjectName, #cnames').blur(function() {
            self.validate();
        });*/

    },

    /* 初始化表格 */
    initGrid: function() {
        gridObj = $.fn.bsgrid.init('projectTable', {
            dataType: 'json',
            url: 'projectQuery',
            pageSize: 10,
            pageSizeSelect: true,
            pageSizeForGrid: [5, 10, 15, 20],
            displayBlankRows: false,
            stripeRows: true,
            rowHoverColor: true,
            lineWrap: true
        });
    },

    operate: function (record, rowIndex, colIndex, options) {
        var isValid = gridObj.getRecordIndexValue(record, 'is_valid');
        var pid = gridObj.getRecordIndexValue(record, 'id');
        var operate = '';
        var permission = $('#permission').val();
        if(isValid == 0){
            operate = '<button type="button" class="btn btn-xs btn-primary s-w50" onclick="project.showDialog('+'\'修改项目\','+ rowIndex + ');">修改</button>  ';
            if(pid != 4){
                operate += '<button type="button" class="btn btn-xs btn-primary s-w50" onclick="project.del(' + gridObj.getRecordIndexValue(record, 'id') + ');">删除</button>';
            }
        }
        return operate;
    },

    renderIsValid: function (record, rowIndex, colIndex, options) {
        var isValid = gridObj.getRecordIndexValue(record, 'is_valid');
        var value = (isValid == 0) ?  '生效' : '<span class="red">已删除</span>';
        return value;
    },

    renderStatus: function (record, rowIndex, colIndex, options) {
        var status = gridObj.getRecordIndexValue(record, 'status');
        var arr = ['0', '1', '2'];
        var translateArr = ['未开始', '进行中', '已完成'];
        var index = arr.indexOf(status);
        return translateArr[index];
    },

    /* 项目查询 */
    query: function(params, gridObj) {
        gridObj.search(params);
    },

    /* 查询项目负责人 */
    getProjectUsers: function(){
        $.ajax({
            url: '/admin/projectUsers',
            type: 'POST',
            success: function(data) {
                $.each(data, function (index, value) {
                    $('#uid').append('<option value="' + value.id + '">' + value.name + '</option>');
                });
            },
            error:function(data){
                console.error(data);
            }
        });
    },

    /* 查询配置人员 */
    getProjectMembers: function() {
        var self = this;
        $('#cid').html('');
        $.ajax({
            url: '/admin/projectJoinUsers',
            type: 'POST',
            success: function(data) {
                $.each(data, function (index, value) {
                    $('#cid').append('<label><input type="checkbox" id="cid'+value.id+'" value="' + value.id + '"><span class="member">'+ value.name +'</span></label> ');
                    if((index + 1) % 5 == 0){
                        $('#cid').append('<br>');
                    }
                });
                $('#cid input').click(function() {
                    self.checkedMember();
                });
            },
            error:function(data){
                console.error(data);
            }
        });
    },

    /* 打开对话框 */
    showDialog: function(title, rowIndex) {
        var self = this;
        $('#showIsValid').hide();
        $('#title').text(title);
        self.clearForm();
        if (rowIndex >= 0) {
            var rowRecord = gridObj.getRecord(rowIndex);
            $('#showIsValid').show();
            $('#editProjectId').val(rowRecord.id);
            $('#editProjectName').val(rowRecord.name);
            $('#beginDate').val(rowRecord.begin_date);
            $('#endDate').val(rowRecord.end_date);
            $('#uid').val(rowRecord.uid);
            $('#editStatus').val(rowRecord.status);
            $('#editIsValid').val(rowRecord.is_valid);
            self.getCheckedMember(rowRecord.cid);
        }
        $('#dialog').modal('show');

        $('#beginDate,#endDate').datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 2,
            minView: 2,
            autoclose: true,
            language: 'zh-CN',
            todayBtn: true,
        });
    },

    /* 关闭对话框 */
    closeDialog: function() {
        $('#dialog').modal('hide');
    },

    /* 清空对话框表单 */
    clearForm: function() {
        $('#cid input:checked').attr('checked', false);
        $('#dialogForm')[0].reset();
        $('#errMsg').text('');
        /*$('#errMemberMsg').text('');*/
        $('#dialogForm .error').text('');
    },

    /* 确认新增/修改项目 */
    confirm: function() {
        var self = this;
        var id = $('#editProjectId').val();
        var params = {
            name : $.trim($('#editProjectName').val()),
            beginDate : $('#beginDate').val(),
            endDate : $('#endDate').val(),
            status : $('#editStatus').val(),
            isValid : $('#editIsValid').val(),
            uid : $('#uid').val(),
            cids : $('#cids').val()
        }
        if(id){
            params = $.extend(params, {id : id});
        }

        $.ajax({
            url : '/admin/projectSave',
            type : 'POST',
            data : params,
            success : function(data){
                self.query({}, gridObj);
                self.closeDialog();
                block.showMsg('操作成功');
            },
            error : function(data){
                console.error(data);
            }
        });
    },

    /* 删除项目 */
    del: function(projectId) {
        var self = this;
        if(confirm('确认删除？')){
            $.ajax({
                url : '/admin/projectDelete',
                type : 'POST',
                data : {
                    id : projectId
                },
                success : function(data){
                    self.query({}, gridObj);
                },
                error : function(data){
                    console.error(data);
                }
            });
        } else {
            return;
        }
    },

    /* 批量删除 */
    batchDelete: function() {
        var self = this;
        var ids = gridObj.getCheckedValues('id');
        console.log(ids);
        if(ids.length == 0){
            // my.public.message('请选择记录！');
            block.showMsg('请选择至少一条记录！');
        } else {
            if(confirm('确认删除？')){
                $.ajax({
                    url : '/admin/projectDelete',
                    type : 'POST',
                    data : {
                        id : ids + ''
                    },
                    success : function(data){
                        self.query({}, gridObj);
                    }
                });
            } else {
                return;
            }
        }
    },

    /* 检查项目名唯一性 */
    /*checkProjectName: function(cb) {
        var self = this;
        var params = {
            id : $('#editProjectId').val(),
            name : $('#editProjectName').val()
        }
        $.post('/admin/checkProjectName', params, function(data){
            $('#errMsg').text(data.msg);
            console.log(data);
            self.code = data.result;
            console.log(self.code);
            // cb(data.result);
        });
    },*/

    /* 表单验证 */
    /*validate: function() {
        var self = this;
        var name = $.trim($('#editProjectName').val());
        var member = $.trim($('#cnames').val());
        var flag = false;
        if(name == '') {
            $('#errMsg').text('请填写项目名');
            flag = false;
        } else {
            flag = true;
        }
        if(member == '') {
            $('#errMemberMsg').text('请选择项目成员');
            flag = false;
        } else {
            // $('#errMemberMsg').text('');
            flag = true;
        }
        return flag;
    },*/

    /*[{'#errMsg':'请填写项目名'}].forEach(function(){

    })*/

    /* code 用于验证 */
    /*code: true,*/

    /* 选择配置人员 */
    checkedMember: function() {
        var names = '';
        var ids = '';
        $('#cid input:checked').each(function() {
            ids += ',' + $(this).val();
            names += ', ' + $(this).next().text();
        });
        $('#cids').val(ids.substring(1));
        $('#cnames').val(names.substring(1));
    },

    /* 修改项目时获取项目参与成员 */
    getCheckedMember: function(pid) {
        var self = this;
        var pids = pid.split(',');
        for(var i = 0; i < pids.length; i++){
            // console.log(pids[i]);
            $('#cid'+ $.trim(pids[i])).attr('checked', true);
        }
        self.checkedMember();
    },

    /* 表单验证 */
    validate: function(){
        $.validator.addMethod('isSmaller', function(value, element) {
            var beginDate = $('#beginDate').val();
            return this.optional(element) || (new Date(value) >= new Date(beginDate));
        }, '结束时间小于开始时间');

        $('#dialogForm').validate({
            rules: {
                editProjectName: {
                    required: true,
                    remote: {
                        url: '/admin/checkProjectName',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            id: function(){
                                return $('#editProjectId').val();
                            },
                            name: function(){
                                return $('#editProjectName').val()
                            }
                        }
                    }
                },
                endDate: {
                    isSmaller: true,
                    date: true
                },
                beginDate: {
                    date: true
                },
                uid: 'required',
                cnames: 'required',
            },
            messages: {
                editProjectName: {
                    required: '请填写项目名',
                    remote: '项目名已存在'
                },
                endDate:{
                    date: '请正确填写日期'
                },
                beginDate:{
                    date: '请正确填写日期'
                },

                uid: '请选择项目负责人',
                cnames: '请选择项目成员',
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.parents('.form-group'));
            }

        });
    },
};
project.init();
